package org.scboy.rbac.service.imp;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.rbac.dao.RbacLoginSessionDao;
import org.scboy.rbac.dao.RbacLoginStateDao;
import org.scboy.rbac.dao.RbacMenusDao;
import org.scboy.rbac.dao.RbacPermissionDao;
import org.scboy.rbac.dao.RbacResourcePermissionDao;
import org.scboy.rbac.dao.RbacUserInfoDao;
import org.scboy.rbac.service.PermissionService;
import org.scboy.utils.entitys.coobi.Model;
import org.scboy.utils.entitys.coobi.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.core.lang.UUID;


/**
 * 
 * 权限业务类
 * @author yanghao
 *
 */

@Service
public class PermissionServiceImp implements PermissionService {

	@Autowired
	EntityFactory factory;
	
	  /**
	   * 分页查询权限
	   * @param model 查询参数
	   * @return
	   */		  
	@Override
	public Page page(Model model) {
		RbacPermissionDao dao=factory.getDao(RbacPermissionDao.class);
		model.orderBy("permCode");
		return dao.page(model);
	}
	
	  /**
	   * 新增权限
	   * @param model 权限Model
	   * @return
	   */	
	@Override
	public boolean add(Model model) {
		RbacPermissionDao dao=factory.getDao(RbacPermissionDao.class);
		model.add("id", UUID.randomUUID().toString());
		if(model.getString("permParams")==null){
			model.add("permParams", "");
		}
		model.add("addTime", new Date());
		model.add("editTime", new Date());
		if(dao.count(
				Model.create()
				.add("menuId", model.getString("menuId"))
				.add("permCode", model.getString("permCode")))>0){
			return false;
		}
		int result=dao.insert(model);
		if(result>0){
			return true;
		}else{
			return false;
		}
	}
	
	 /**
	   * 删除权限
	   * @param id 权限ID
	   * @return
	   */	
	@Override
	@Transactional
	public boolean delete(String id) {
		RbacPermissionDao dao=factory.getDao(RbacPermissionDao.class);
		RbacResourcePermissionDao resPermDao=factory.getDao(RbacResourcePermissionDao.class);
		resPermDao.delete(Model.create().add("permId", id));
		int result=dao.delete(Model.create().add("id", id));
		if(result>0){
			return true;
		}else{
			return false;
		}
	}
	
	 /**
	   * 更新权限
	   * @param model 权限Model
	   * @return
	   */	
	@Override
	public boolean update(Model model) {
		RbacPermissionDao dao=factory.getDao(RbacPermissionDao.class);
		model.add("editTime", new Date());
		if(dao.count(
				Model.create()
				.add("menuId", model.getString("menuId"))
				.NE("id", model.getString("id"))
				.add("permCode", model.getString("permCode")))>0){
			return false;
		}
		int result=dao.update(model,Model.create().add("id", model.getString("id")));
		if(result>0){
			return true;
		}else{
			return false;
		}
	}
	
	 /**
	   * 启用禁用权限
	   * @param id 权限ID
	   * @return
	   */	
	@Override
	public boolean checkState(String id) {
		RbacPermissionDao dao=factory.getDao(RbacPermissionDao.class);
		Model model=get(id);
		if(model==null){
			return false;
		}
		model.add("permAction", !model.getBoolean("permAction"));
		int resultCount=dao.update(model);
		if(resultCount>0){
			return true;
		}else{
			return false;
		}
	}
	
	 /**
	   * 根据权限ID获取权限信息
	   * @param id 权限ID
	   * @return
	   */
	@Override
	public Model get(String id) {
		RbacPermissionDao dao=factory.getDao(RbacPermissionDao.class);
		return dao.get(Model.create().add("id", id));
	}

	@Override
	public List<Model> route(String systemId,String token) {

		RbacLoginStateDao stateDao=factory.getDao(RbacLoginStateDao.class);
		RbacUserInfoDao userInfoDao=factory.getDao(RbacUserInfoDao.class);

		Model loginState=stateDao.get(Model.create().add("sessionId", token).add("sessionState", 0));
		if(loginState!=null) {
			String userId=loginState.getString("userId");
			//检查用户是不是超级管理员
			long count=userInfoDao.count(Model.create().add("id", userId).add("userType", "administrator"));
			if(count>0) {
				List<Model> routes=loadAdminMenus(systemId, "root");
				return routes;
			}else {
				List<Model> routes=loadMenus(userId, systemId, "root");
				return routes;
			}
		}else {
			return new ArrayList<Model>();
		}
	}
	
	
	public List<Model> loadMenus(String userId,String sysId,String parentId){
		List<Model> routes =new ArrayList<Model>();
		RbacLoginSessionDao dao=factory.getDao(RbacLoginSessionDao.class);
		List<Model> listMenus=dao.queryUserMenus(Model.create().add("userId", userId)
				.add("sysId", sysId)
				.add("parentId", parentId));
		for (Model model : listMenus) {
			
			//构建route对象
			Model route=Model.create();
			route.add("name", model.getString("menuName"));
			route.add("component", model.getString("menuComponent"));
			route.add("path", model.getString("menuPath"));
			route.add("redirect", model.getString("menuRedirect"));
			route.add("name", model.getString("menuName"));
			//构建route的Meta配置对象
			Model meta=Model.create();
			meta.add("hidden", model.getBoolean("menuHidden"));
			meta.add("alwaysShow", model.getBoolean("alwaysShow"));
			meta.add("title", model.getString("menuTitle"));
			meta.add("icon", model.getString("menuIcon"));
			meta.add("noCache", model.getBoolean("noCache"));
			meta.add("breadcrumb", model.getBoolean("breadcrumb"));
			meta.add("affix", model.getBoolean("affix"));
			meta.add("activeMenu", model.getString("activeMenu"));
			meta.add("noTagsView", model.getBoolean("noTagsView"));
			meta.add("canTo", model.getBoolean("canTo"));
			//加载权限配置
			List<Model> listPermissions=dao.queryUserPermissions(Model.create().add("userId", userId).add("menuId", model.getString("id")));
			String [] permission=new String[listPermissions.size()];
			for (int i=0;i<listPermissions.size();i++) {
				permission[i]=listPermissions.get(i).getString("permCode");
			}
			meta.add("permission", permission);
			//添加配置对象
			route.add("meta", meta);
			
			//查询是否有子菜单
			List<Model> children=loadMenus(userId, sysId, model.getString("id"));
			if(children.size()>0) {
				route.add("children", children);
			}
			routes.add(route);
		}
		return routes;
	}


	public List<Model> loadAdminMenus(String sysId,String parentId){
		
		List<Model> routes =new ArrayList<Model>();
		
		RbacMenusDao menusDao=factory.getDao(RbacMenusDao.class);
		RbacPermissionDao permissionDao=factory.getDao(RbacPermissionDao.class);
		
		List<Model> listMenus=menusDao.select(Model.create()
				.add("sysId", sysId)
				.add("menuAction", 1)
				.add("parentId", parentId)
				.orderBy("menuSort"));
		for (Model model : listMenus) {
			
			//构建route对象
			Model route=Model.create();
			route.add("name", model.getString("menuName"));
			route.add("component", model.getString("menuComponent"));
			route.add("path", model.getString("menuPath"));
			route.add("redirect", model.getString("menuRedirect"));
			route.add("name", model.getString("menuName"));
			//构建route的Meta配置对象
			Model meta=Model.create();
			meta.add("hidden", model.getBoolean("menuHidden"));
			meta.add("alwaysShow", model.getBoolean("alwaysShow"));
			meta.add("title", model.getString("menuTitle"));
			meta.add("icon", model.getString("menuIcon"));
			meta.add("noCache", model.getBoolean("noCache"));
			meta.add("breadcrumb", model.getBoolean("breadcrumb"));
			meta.add("affix", model.getBoolean("affix"));
			meta.add("activeMenu", model.getString("activeMenu"));
			meta.add("noTagsView", model.getBoolean("noTagsView"));
			meta.add("canTo", model.getBoolean("canTo"));
			//加载权限配置
			List<Model> listPermissions=permissionDao.select(Model.create().add("menuId", model.getString("id")).add("permAction", 1));
			String [] permission=new String[listPermissions.size()];
			for (int i=0;i<listPermissions.size();i++) {
				permission[i]=listPermissions.get(i).getString("permCode");
			}
			meta.add("permission", permission);
			//添加配置对象
			route.add("meta", meta);
			
			//查询是否有子菜单
			List<Model> children=loadAdminMenus(sysId, model.getString("id"));
			if(children.size()>0) {
				route.add("children", children);
			}
			routes.add(route);
		}
		return routes;
	}
	
}
